#include <libusb-1.0/libusb.h>
#include <stdio.h>

int main(void) {
  libusb_context *ctx = NULL;
  int r = libusb_init(&ctx);
  if (r < 0) {
    fprintf(stderr, "Failed to initialize libusb: %s\n", libusb_error_name(r));
    return 1;
  }

  libusb_device **devs = NULL;
  ssize_t cnt = libusb_get_device_list(ctx, &devs);
  if (cnt < 0) {
    fprintf(stderr, "Error getting device list: %s\n", libusb_error_name(cnt));
    libusb_exit(ctx);
    return 1;
  }

  printf("Found %zd USB devices:\n", cnt);

  for (ssize_t i = 0; i < cnt; i++) {
    libusb_device *dev = devs[i];
    struct libusb_device_descriptor desc;
    if (libusb_get_device_descriptor(dev, &desc) != 0)
      continue;

    printf("Device %zd: VID=0x%04x, PID=0x%04x\n", i, desc.idVendor,
           desc.idProduct);

    libusb_device_handle *handle = NULL;
    if (libusb_open(dev, &handle) == 0) {
      unsigned char str[256];

      // 获取厂商字符串
      if (desc.iManufacturer &&
          libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, str,
                                             sizeof(str)) > 0) {
        printf("  Manufacturer: %s\n", str);
      } else {
        printf("  Manufacturer: Unknown\n");
      }

      // 获取产品字符串
      if (desc.iProduct && libusb_get_string_descriptor_ascii(
                               handle, desc.iProduct, str, sizeof(str)) > 0) {
        printf("- Product: %s\n", str);
      } else {
        printf("- Product: Unknown\n");
      }

      libusb_close(handle);
    } else {
      printf("- No permission\n");
    }
  }

  libusb_free_device_list(devs, 1);
  libusb_exit(ctx);
  return 0;
}
